package cn.edu.anan.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 检查登录切面
 *
 * @author ThinkPad
 * @version 1.0
 * @date 2021/8/10 20:56
 */
@Aspect
@Component
@Slf4j
public class CheckLoginAspect {

    /**
     * 注入HttpServletRequest
     */
    @Autowired
    private HttpServletRequest request;

    /**
     * 环绕通知
     * @param pjp
     * @return
     */
    @Around("@annotation(cn.edu.anan.aop.NeedLogin)")
    public Object checkLogin(ProceedingJoinPoint pjp) throws Throwable{

        // 1.取出目标方法参数、方法名称
        Object[] args = pjp.getArgs();
        String method = pjp.getSignature().getName();
        log.info("正在访问资源：{},参数：{}", method, args);

        // 2.取出请求参数
        String userId = request.getParameter("userId");
        if(StringUtils.isEmpty(userId)){
            log.error("资源：{}被禁止访问，原因是该资源需要登录以后才能访问.", method);
            throw new RuntimeException("资源：{" + method + "}受保护，需要登录以后才能访问.");
        }

        // 3.放行，执行目标方法
        return pjp.proceed(args);
    }
}
